package org.struts.mvc.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.struts.mvc.StrutsConfig;
import org.struts.mvc.action.Action;
import org.struts.mvc.action.form.ActionForm;
import org.struts.mvc.util.StrutsRequestUtil;

public class ActionServlet extends HttpServlet{

	
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String path = request.getServletPath();
		System.out.println("path=="+path);
		path = path.split("\\.")[0];
		System.out.println("path.split=="+path);
		try {
			@SuppressWarnings("unchecked")
			Map<String,StrutsConfig> strutsConfigMap = (Map<String, StrutsConfig>)this.getServletContext().getAttribute("struts");
			
			StrutsConfig strutsConfig = strutsConfigMap.get(path);
			ActionForm actionForm = StrutsRequestUtil.fullForm(strutsConfig.getBeanClass(), request);
			Action action = (Action) StrutsRequestUtil.getClassByName(strutsConfig.getActionClass());
			String url = action.execute(request, actionForm, strutsConfig.getForwardMap());
			RequestDispatcher dispatcher = request.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
